package IO.stream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectStream {
    static class Obj implements Serializable {
        private String msg;

        public Obj(String msg) {
            this.msg = msg;
        }

        @Override
        public String toString() {
            String name = this.getClass().getName();
            return String.format("%s{msg: %s}", name, msg);
        }
    }

    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("obj.dat");
        ObjectOutputStream objOut = new ObjectOutputStream(fos);
        FileInputStream fis = new FileInputStream("obj.dat");
        ObjectInputStream objIn = new ObjectInputStream(fis);
        try {
            Obj obj = new Obj("hello");
            objOut.writeObject(obj);
            objOut.flush();
            objOut.close();
            Obj objData = (Obj) objIn.readObject();
            System.out.println(objData);
            objIn.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
